// User.js
import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import { useParams, Link, useNavigate } from 'react-router-dom';
// import '../static/css/app.css'; // 导入 CSS 文件
import ActivityListABI from '../contract/ABIs/ActivityList.json'; // 活动列表合约 ABI
import MaterialListABI from '../contract/ABIs/MaterialList.json'; // 材料列表合约 ABI
import UserListABI from '../contract/ABIs/UserList.json'; // 用户列表合约 ABI 
import UserABI from '../contract/ABIs/User.json'; // 用户合约 ABI

import ActivityListAddress from '../contract/ADDRESSes/ActivityListAddress.js'; // 活动列表合约地址
import MaterialListAddress from '../contract/ADDRESSes/MaterialListAddress.js'; // 材料列表合约地址
import UserListAddress from '../contract/ADDRESSes/UserListAddress'; // 用户列表合约地址
import UserNavBar from './nav/UserNavBar.js';
// import '../static/indexcss/aacsss.css';
import Eye from './Eye.js'

const User = () => {
    const [web3, setWeb3] = useState(null);
    // 使用 useParams 获取路由参数中的地址信息
    const { address } = useParams();
    const [contractActivityList, setcontractActivityList] = useState(null);
    const [contractMaterialList, setcontractMaterialList] = useState(null);
    const [contractUserList, setContractUserList] = useState(null);
    const [contractUser, setcontractUser] = useState(null);
    const [isUser, setisUser] = useState(false);
    const [userName, setUserName] = useState('');
    const [idNumber, setIdNumber] = useState('');
    const [password, setPassword] = useState('');
    const [passwordAgain, setPasswordAgain] = useState('');

    const navigate = useNavigate();

    useEffect(() => {
        async function init() {
            // 连接到以太坊网络
            if (window.ethereum) {
                const web3Instance = new Web3(window.ethereum);
                try {
                    // 请求用户授权
                    await window.ethereum.enable();
                    setWeb3(web3Instance);

                    // 创建活动列表合约实例
                    const activityListInstance = new web3Instance.eth.Contract(
                        ActivityListABI,
                        ActivityListAddress
                    );
                    setcontractActivityList(activityListInstance);

                    // 创建材料列表合约实例
                    const materialListInstance = new web3Instance.eth.Contract(
                        MaterialListABI,
                        MaterialListAddress
                    );
                    setcontractMaterialList(materialListInstance);

                    // 创建用户列表合约实例
                    const userListInstance = new web3Instance.eth.Contract(
                        UserListABI,
                        UserListAddress
                    );
                    setContractUserList(userListInstance);

                    // 创建用户合约实例
                    const userInstance = new web3Instance.eth.Contract(
                        UserABI,
                        address
                    );
                    setcontractUser(userInstance);

                    // 获取当前用户的以太坊账户地址
                    const accounts = await web3Instance.eth.getAccounts();
                    const currentAddress = accounts[0];
                    // 获取用户合约的 owner 地址
                    const ownerAddress = await userInstance.methods.getUserAddr().call();
                    // 检查当前账户是否是用户本人
                    setisUser(currentAddress === ownerAddress);
                    // 获取用户信息  
                    const userInfoResult = await userInstance.methods.getOwnerInfo().call();

                    // 根据合约返回的信息更新状态  
                    if (userInfoResult) {
                        setUserName(userInfoResult[0] || ''); //第一个元素是用户名  
                        setIdNumber(userInfoResult[2] || ''); // 第二个元素是学号
                    }
                } catch (error) {
                    console.error(error);
                }
            } else {
                console.error('请安装以太坊浏览器插件，如 MetaMask');
            }
        }
        init();
    }, [address]);


    // 检查密码是否匹配
    const passwordsMatch = () => {
        return password === passwordAgain;
    }

    // 用户修改密码函数
    const modifyPassword = async () => {
        try {
            const accounts = await web3.eth.getAccounts();
            const fromAddress = accounts[0];
            console.log("fromAddress:", fromAddress, "Input:", password, passwordAgain);
            // 检查是否所有字段都有值
            if (!password && !passwordAgain) {
                alert('请填写所有字段再进行修改！');
                return;
            }

            if (!passwordsMatch()) {
                alert('两次输入的密码不匹配，请重新输入！');
                return;
            } else {
                await contractUser.methods.modifyPassword(password).send({ from: fromAddress });
            }

            alert('用户信息修改成功，请重新登录！');
            navigate('/');
        } catch (error) {
            console.error('Error updating user information:', error);
            alert('用户信息修改失败！');
        }
    };


    return (
        <div>
            {/* 如果当前账户不是用户，则显示提示信息 */}
            {!isUser && (<div>您没有权限访问此页面。</div>)}

            {/* 用户界面 */}
            {isUser && (
                <div>

                    <UserNavBar address={address} />
                    <main className="page hire-me-page">
                        <section className="portfolio-block hire-me">
                            <div className="foreground-component">
                                <Eye />
                                <div className="container">
                                    <div className="border rounded border-0 shadow-lg p-3 p-md-5"
                                        data-bs-theme="light"
                                        style={{
                                            backgroundColor: 'rgba(36, 36, 41, 0.6)'
                                        }}
                                    >
                                        <div className="mb-3">
                                            <h1>更改密码</h1>

                                            <div className="mb-3">
                                                <label className="form-label" htmlFor="name">真实姓名</label>
                                                <input className="form-control item" id="name" type="text" placeholder="真实姓名" disabled value={userName} onChange={(e) => setUserName(e.target.value)} />
                                            </div>
                                            <div className="mb-3">
                                                <label className="form-label" htmlFor="name">学号</label>
                                                <input className="form-control item" id="name" type="text" placeholder="学号" disabled value={idNumber} />
                                            </div>
                                            <div className="mb-3">
                                                <label className="form-label" htmlFor="name">密码</label>
                                                <input className="form-control item" id="name" type="password" placeholder="密码" value={password} onChange={(e) => setPassword(e.target.value)} />
                                            </div>
                                            <div className="mb-3">
                                                <label className="form-label" htmlFor="name">再次确认密码</label>
                                                <input className="form-control item" id="name" type="password" placeholder="再次确认密码" value={passwordAgain} onChange={(e) => setPasswordAgain(e.target.value)} />
                                            </div>
                                            <div className="mb-3 mt-4">
                                                <button className="btn btn-primary btn-lg d-block w-100" onClick={modifyPassword}>修改</button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </section>
                    </main>
                </div>
            )}
        </div>
    );
}

export default User;
